package com.example.orderminiappapi.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.example.orderminiappapi.bean.Response;
import com.example.orderminiappapi.bean.SearchCondition;
import com.example.orderminiappapi.bean.Shop;
import com.example.orderminiappapi.service.NoticeService;
import com.example.orderminiappapi.service.SearchService;
import com.example.orderminiappapi.utils.webSocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RestController
@CrossOrigin
public class NoticeController {
    @Autowired
    private NoticeService noticeService;

    /**
     * 获取该商店下未读的信息
     */
    @ResponseBody
    @RequestMapping(value = "/getUnreadNotice", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response getUnreadNotice(HttpServletRequest request) throws IOException {
        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String shopId = verify.getClaim("shopId").asString();

        Shop shop = new Shop();
        shop.setShopId(shopId);

        Response response = new Response("10000", "成功", noticeService.getUnreadNotice(shop));
        return response;
    }

    /**
     * 获取该商店下的信息
     */
    @ResponseBody
    @RequestMapping(value = "/getAllNotice", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response getAllNotice(HttpServletRequest request,@RequestBody SearchCondition searchCondition) throws IOException {
        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String shopId = verify.getClaim("shopId").asString();

        searchCondition.setId(shopId);

        searchCondition.setData(noticeService.getAllNotice(searchCondition));
        searchCondition.setTotal(noticeService.getNoticeCount(searchCondition));

        Shop shop = new Shop();
        shop.setShopId(shopId);
        int flag = noticeService.readAllNotice(shop);
        if(flag > 0) {
            WebSocketServer.sendInfo("阅读完毕", shop.getShopId());
        }

        Response response = new Response("10000", "成功", searchCondition);
        return response;
    }
}
